from pygame import mixer
import time

class Voice:
    def __init__(self):
        mixer.init()
        self.dict = {"dougan": r"E:\Innovative Practice\MyProject\voice\get_dougan.mp3",
                     "laolaobei": r"E:\Innovative Practice\MyProject\voice\get_laolaobei.mp3",
                     "nailaoxiaowanzi": r"E:\Innovative Practice\MyProject\voice\get_nailaoxiaowanzi.mp3",
                     "qinzuishao": r"E:\Innovative Practice\MyProject\voice\get_qinzuishao.mp3",
                     "shengyenatie": r"E:\Innovative Practice\MyProject\voice\get_shengyenatie.mp3",
                     "shuimitaoguozhi": r"E:\Innovative Practice\MyProject\voice\get_shuimitaoguozhi.mp3",
                     "wanzaimian": r"E:\Innovative Practice\MyProject\voice\get_wanzaimian.mp3",
                     "xingqiubei": r"E:\Innovative Practice\MyProject\voice\get_xingqiubei.mp3",
                     "xizhilang": r"E:\Innovative Practice\MyProject\voice\get_xizhilang.mp3"}

    def play(self, name=None, path=None, block=True):
        """
        播放音频文件
        
        Args:
            name: 预定义的音频名称
            path: 自定义音频路径
            block: 是否阻塞直到音频播放完成
        """
        if path:
            try:
                mixer.music.load(path)
                mixer.music.play()
            except Exception as e:
                print(f"播放失败: {e}")
                return
        elif name in self.dict:
            try:
                mixer.music.load(self.dict[name])
                mixer.music.play()
            except Exception as e:
                print(f"播放失败: {e}")
                return
        else:
            print("音频名称或路径不存在")
            return
            
        # 阻塞直到音频播放完成
        if block:
            while mixer.music.get_busy():
                time.sleep(0.1)

if __name__ == '__main__':
    v = Voice()
    v.play(path="E:/Innovative Practice/MyProject/voice/init_camera_done.mp3")
    v.play(path=r"E:\Innovative Practice\MyProject\voice\welcome.mp3")
    v.play(name="dougan")
    v.play(name="laolaobei")